import mysql.connector


class MySQLDB:
    def __init__(self, host, user, password, database):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.connection = None
        self.cursor = None

    def connect(self):
        self.connection = mysql.connector.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database
        )
        self.cursor = self.connection.cursor()

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()

    def execute(self, query, params=None):
        if not self.cursor:
            raise Exception("Cursor is not initialized. Please connect to the database first.")
        if params:
            self.cursor.execute(query, params)
        else:
            self.cursor.execute(query)
        return self.cursor.fetchall()

    def execute_commit(self, query, params=None):
        if not self.cursor:
            raise Exception("Cursor is not initialized. Please connect to the database first.")
        if params:
            self.cursor.execute(query, params)
        else:
            self.cursor.execute(query)
        return self.connection.commit()


# 测试用

db = MySQLDB("10.200.32.179", "root", "111111", "zhangqing")
db.connect()

# 查询 images_qa 表中的所有数据
print(db.execute("SELECT * FROM images_qa"))

# 向 images_qa 表中插入一条新记录
# db.execute("直接给insert sql")
# 更新 images_qa 表中的一条记录
# db.execute("直接给update sql")
# 删除 images_qa 表中的一条记录
# 假设我们要删除 id 为 3 的记录
print(db.execute_commit("delete from images_qa where id = 10"))

db.close()
